package com.bfsuol.bfsuolframework.core.synchronization;

import com.bfsuol.bfsuolframework.core.utils.StringUtils;
import org.jgroups.util.Streamable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;


public class SyncGroupCommand implements Streamable{
		
		public static final int ACTION_PUT  = 1;
		public static final int ACTION_REMOVE = 2;
		public static final int ACTION_RELOAD = 3;
		public static final int ACTION_CLEAR = 4;
		public static final int ACTION_CUSTOM = 5;
	    
		private int action = 1;
		private long id = -1;
		private String params = "";
		
		public SyncGroupCommand(){ }
		public SyncGroupCommand(int action){
			setAction(action);
		}
		public SyncGroupCommand(int action, long id){
			setAction(action);
			setId(id);
		}
		public SyncGroupCommand(int action, long id, String params){
			setAction(action);
			setId(id);
			setParams(params);
		}
		
		/**
		 * @return the action
		 */
		public int getAction() {
			return action;
		}
		/**
		 * @param action the action to set
		 */
		public void setAction(int action) {
			this.action = action;
		}
		/**
		 * @return the id
		 */
		public long getId() {
			return id;
		}
		/**
		 * @param id the id to set
		 */
		public void setId(long id) {
			this.id = id;
		}
		
		
		/**
		 * @return the params
		 */
		public String getParams() {
			return params;
		}
		/**
		 * @param params the params to set
		 */
		public void setParams(String params) {
			if(params==null){
				this.params = "";
				return;
			}
			if(params.length() > 10000){
				this.params = params.substring(0, 10000) + "...";
			}
			this.params = params;
		}
		
		public void writeTo(DataOutput out) throws IOException {
	        out.writeInt(getAction());
	        out.writeLong(getId());
	        out.writeUTF(getParams());
	    }

	    public void readFrom(DataInput in) throws IOException, IllegalAccessException, InstantiationException {
	        setAction(in.readInt());
	        setId(in.readLong());
	        setParams(in.readUTF());
	    }


	    public String toString() {
	        StringBuilder ret=new StringBuilder();
	        switch(action) {
	            case ACTION_PUT: 
	            	ret.append("PUT");
	                break;
	            case ACTION_REMOVE: 
	            	ret.append("REMOVE");
	                break;
	            case ACTION_RELOAD: 
	            	ret.append("RELOAD");
                	break;
	            case ACTION_CLEAR: 
	            	ret.append("CLEAR");
                	break;
	            case ACTION_CUSTOM: 
	            	ret.append("CUSTOM");
	            	break;
	            default:
	                return "<undefined>";
	        }
	        if(id>-1){
        		ret.append("(").append(id).append(")");
        	}
	        if(!StringUtils.isBlank(params)){
        		ret.append("#").append(params);
        	}
	        return ret.toString();
	    }
	}
